<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px" class="three-column-form">
      <el-form-item label="管理单位" prop="belongOrgId">
        <treeselect
          v-model="queryParams.belongOrgId"
          :options="deptOptions"
          :normalizer="normalizer"
          :show-count="true"
          placeholder="请选择管理单位"
          @select="handleDeptSelect"
        />
      </el-form-item>
      <el-form-item label="用电分类" prop="elecTypeCode">
        <el-select v-model="queryParams.elecTypeCode" placeholder="请选择用电分类" clearable>
          <el-option
            v-for="dict in dict.type.elec_type_code"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="电价码" prop="prcCode">
        <el-input
          v-model="queryParams.prcCode"
          placeholder="请输入电价码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电价类别" prop="elecTypeCode1">
        <el-select v-model="queryParams.elecTypeCode1" placeholder="请选择电价类别" clearable>
          <el-option
            v-for="dict in dict.type.elec_type_code1"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['config:config:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['config:config:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['config:config:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['config:config:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed/>
      <el-table-column type="index" label="序号" width="50" align="center" fixed/>
      <el-table-column label="管理单位" align="center" prop="deptName" width="200"/>
      <el-table-column label="用电分类" align="center" prop="elecTypeCode" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.elec_type_code" :value="scope.row.elecTypeCode"/>
        </template>
      </el-table-column>
      <el-table-column label="电价码" align="center" prop="prcCode" width="100"/>
      <el-table-column label="电价类别" align="center" prop="elecTypeCode1" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.elec_type_code1" :value="scope.row.elecTypeCode1"/>
        </template>
      </el-table-column>
      <el-table-column label="电压等级" align="center" prop="voltageClass" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.voltage_class" :value="scope.row.voltageClass"/>
        </template>
      </el-table-column>
      <el-table-column label="执行日期段" align="center" prop="execDate" width="250">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.exec_date" :value="scope.row.execDate"/>
        </template>
      </el-table-column>
      <el-table-column label="渠道编码" align="center" prop="channelCode" width="250">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.channel_code" :value="scope.row.channelCode"/>
        </template>
      </el-table-column>
      <el-table-column label="执行时间段" align="center" prop="electricityExecTimeList" width="250">
        <template slot-scope="scope">
          <dict-tag 
            v-if="scope.row.electricityExecTimeList && scope.row.electricityExecTimeList.length > 0"
            :options="dict.type.exec_time" 
            :value="scope.row.electricityExecTimeList[0].timePeriodCode"
          />
        </template>
      </el-table-column>
      <el-table-column label="执行电价(元)" align="center" prop="electricityExecTimeList" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.electricityExecTimeList && scope.row.electricityExecTimeList.length > 0">
            {{ scope.row.electricityExecTimeList[0].price }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['config:config:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['config:config:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改电价配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="管理单位" prop="belongOrgId">
              <treeselect
                v-model="form.belongOrgId"
                :options="deptOptions"
                :normalizer="normalizer"
                placeholder="请选择管理单位"
                @select="(node) => { form.belongOrgName = node.deptName }"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用电分类" prop="elecTypeCode">
              <el-select v-model="form.elecTypeCode" placeholder="请选择用电分类" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.elec_type_code"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="电价码" prop="prcCode">
              <el-input v-model="form.prcCode" placeholder="请输入电价码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电价类别" prop="elecTypeCode1">
              <el-select v-model="form.elecTypeCode1" placeholder="请选择电价类别" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.elec_type_code1"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="电压等级" prop="voltageClass">
              <el-select v-model="form.voltageClass" placeholder="请选择电压等级" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.voltage_class"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行日期段" prop="execDate">
              <el-select v-model="form.execDate" placeholder="请选择执行日期段" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.exec_date"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="渠道编码" prop="channelCode">
              <el-select v-model="form.channelCode" placeholder="请选择渠道编码" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.channel_code"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center">电价执行时间段信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddElectricityExecTime">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteElectricityExecTime">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="electricityExecTimeList" :row-class-name="rowElectricityExecTimeIndex" @selection-change="handleElectricityExecTimeSelectionChange" ref="electricityExecTime">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="时间段编码" prop="timePeriodCode" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.timePeriodCode" placeholder="请选择时间段编码">
                <el-option
                  v-for="dict in dict.type.exec_time"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <!-- <el-table-column label="执行开始时间" prop="startTime" width="240">
            <template slot-scope="scope">
              <el-date-picker clearable v-model="scope.row.startTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择执行开始时间" />
            </template>
          </el-table-column>
          <el-table-column label="执行结束时间" prop="endTime" width="240">
            <template slot-scope="scope">
              <el-date-picker clearable v-model="scope.row.endTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择执行结束时间" />
            </template>
          </el-table-column> -->
          <el-table-column label="该时间段电价(元/千瓦时)" prop="price" width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.price" placeholder="请输入该时间段电价" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listConfig, getConfig, delConfig, addConfig, updateConfig } from "@/api/config/config"
import { listDept } from "@/api/system/dept"
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"

export default {
  name: "Config",
  components: { Treeselect },
  dicts: ['exec_time', 'elec_type_code', 'elec_type_code1', 'voltage_class', 'exec_date', 'channel_code'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedElectricityExecTime: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 电价配置表格数据
      configList: [],
      // 电价执行时间段表格数据
      electricityExecTimeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 部门树选项
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        belongOrgId: undefined,
        belongOrgName: undefined,
        elecTypeCode: null,
        prcCode: null,
        elecTypeCode1: null,
        voltageClass: null,
        execDate: null
      },
      // 表单参数
      form: {
        id: null,
        belongOrgId: undefined,
        belongOrgName: undefined,
        elecTypeCode: null,
        prcCode: null,
        elecTypeCode1: null,
        voltageClass: null,
        execDate: null
      },
      // 表单校验
      rules: {
        belongOrgId: [
          { required: true, message: "管理单位不能为空", trigger: "blur" }
        ],
        elecTypeCode: [
          { required: true, message: "用电分类不能为空", trigger: "change" }
        ],
        prcCode: [
          { required: true, message: "电价码不能为空", trigger: "blur" }
        ],
        elecTypeCode1: [
          { required: true, message: "电价类别不能为空", trigger: "change" }
        ],
        voltageClass: [
          { required: true, message: "电压等级不能为空", trigger: "change" }
        ],
        execDate: [
          { required: true, message: "执行日期段不能为空", trigger: "change" }
        ],
        channelCode: [
          { required: true, message: "渠道编码不能为空", trigger: "change" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getDeptTree()
  },
  methods: {
    /** 部门选择事件 */
    handleDeptSelect(node) {
      this.queryParams.orgId = node.id
      this.queryParams.orgName = node.label
    },
    /** 查询电价配置列表 */
    getList() {
      this.loading = true
      listConfig(this.queryParams).then(response => {
        this.configList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        belongOrgId: undefined,
        belongOrgName: undefined,
        elecTypeCode: null,
        prcCode: null,
        elecTypeCode1: null,
        voltageClass: null,
        execDate: null
      }
      this.electricityExecTimeList = []
      this.resetForm("form")
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      }
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, "deptId")
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.queryParams.belongOrgName = undefined
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getDeptTree()
      this.open = true
      this.title = "添加配置"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getConfig(id).then(response => {
        this.form = response.data
        this.electricityExecTimeList = response.data.electricityExecTimeList
        this.open = true
        this.title = "修改电价配置"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.electricityExecTimeList = this.electricityExecTimeList
          if (this.form.id != null) {
            updateConfig(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addConfig(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除电价配置编号为"' + ids + '"的数据项？').then(function() {
        return delConfig(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
	/** 电价执行时间段序号 */
    rowElectricityExecTimeIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 电价执行时间段添加按钮操作 */
    handleAddElectricityExecTime() {
      let obj = {}
      obj.timePeriodCode = ""
      obj.startTime = ""
      obj.endTime = ""
      obj.price = ""
      this.electricityExecTimeList.push(obj)
    },
    /** 电价执行时间段删除按钮操作 */
    handleDeleteElectricityExecTime() {
      if (this.checkedElectricityExecTime.length == 0) {
        this.$modal.msgError("请先选择要删除的电价执行时间段数据")
      } else {
        const electricityExecTimeList = this.electricityExecTimeList
        const checkedElectricityExecTime = this.checkedElectricityExecTime
        this.electricityExecTimeList = electricityExecTimeList.filter(function(item) {
          return checkedElectricityExecTime.indexOf(item.index) == -1
        })
      }
    },
    /** 复选框选中数据 */
    handleElectricityExecTimeSelectionChange(selection) {
      this.checkedElectricityExecTime = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('config/config/export', {
        ...this.queryParams
      }, `config_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style>
/* 对话框表单样式 */
.dialog-form {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10px;
}

.dialog-form .el-form-item {
  width: calc(50% - 20px);
  margin: 0 10px 10px;
  box-sizing: border-box;
}

.dialog-form .el-form-item .el-form-item__content {
  width: calc(100% - 120px) !important;
}

/* 输入框和选择框样式 */
.dialog-form .el-form-item .el-input,
.dialog-form .el-form-item .el-select,
.dialog-form .el-form-item .el-date-editor {
  width: 100% !important;
}

.dialog-form .el-form-item .el-input__inner,
.dialog-form .el-form-item .el-select .el-input__inner,
.dialog-form .el-form-item .el-date-editor .el-input__inner {
  width: 100% !important;
}

/* select组件样式 */
.dialog-form .el-form-item .el-select .el-input {
  width: 100% !important;
}

/* 日期组件样式 */
.dialog-form .el-form-item .el-date-editor {
  width: 100% !important;
}

/* 搜索表单样式保持不变 */
.three-column-form .el-form-item .el-form-item__content {
  width: calc(100% - 145px) !important;
}

.three-column-form .el-form-item .el-select {
  width: 100% !important;
}

.three-column-form .el-form-item .el-select .el-input {
  width: 100% !important;
}

.three-column-form .el-form-item .el-select .el-input__inner {
  width: 100% !important;
}

.three-column-form .el-form-item .el-date-editor {
  width: 100% !important;
}

.three-column-form .el-form-item .el-date-editor .el-input__inner {
  width: 100% !important;
}

.three-column-form .el-form-item:last-child .el-form-item__content {
  width: 100% !important;
  margin-left: 0;
  text-align: right;
}

.three-column-form .el-form-item:last-child .el-button {
  margin-left: 10px;
}

/* 添加树形选择器样式 */
.three-column-form .vue-treeselect {
  width: 100%;
}

.three-column-form .vue-treeselect .vue-treeselect__control {
  border-radius: 4px;
}

/* 对话框表单中的树形选择器样式 */
.dialog-form .vue-treeselect {
  width: 100%;
}

.dialog-form .vue-treeselect .vue-treeselect__control {
  border-radius: 4px;
}

/* 逻辑地址输入框样式 */
.logic-address-item .el-form-item__content {
  width: calc(100% - 120px) !important;
}

.logic-address-inputs {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.logic-address-inputs .el-input {
  width: 48% !important;
}

.logic-address-inputs .el-input__inner {
  width: 100% !important;
}

/* 表格容器样式 */
.table-container {
  width: 100%;
  overflow-x: auto;
}

.table-container .el-table {
  min-width: 100%;
}

/* 确保表格内容不会被压缩 */
.table-container .el-table__body-wrapper {
  overflow-x: auto;
}

/* 固定列样式 */
.table-container .el-table__fixed-right {
  height: 100% !important;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.15);
}

.table-container .el-table__fixed {
  height: 100% !important;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.15);
}
</style>

<style scoped>
.three-column-form {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10px;
}

.three-column-form .el-form-item {
  width: calc(33.33% - 20px);
  margin: 0 10px 10px;
  box-sizing: border-box;
}

.three-column-form .el-form-item:last-child {
  width: 100%;
  margin: 0 10px;
  text-align: right;
}
</style>
